package com.lagou.cl.controller;

import com.alibaba.fastjson.JSON;
import com.lagou.cl.pojo.PayOrder;
import com.lagou.cl.service.PayOrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 程  林
 * @date 2020-10-12 00:40
 * @description //
 * @since V1.0.0
 */
@RestController
public class PayController {


	@Autowired
	private PayOrderService payOrderService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@RequestMapping("create")
	public String create() {

		Map<String, Object> res = new HashMap<>();

		try {
			String orderId = new SimpleDateFormat("yyyyMMddHHmmssS").format(new Date());

			PayOrder payOrder = new PayOrder();
			payOrder.setOrderId(orderId);
			payOrder.setMoney(new Random().nextDouble() * 1000 + 1002);
			payOrder.setState(1);
			payOrder.setCreateTime(new Date());
			//
			payOrderService.addOrder(payOrder);

			//
			String pOrder = JSON.toJSONString(payOrder);
			rabbitTemplate.convertAndSend("ex.pay", "key.pay", pOrder.getBytes());

			res.put("code", "0000");
			res.put("msg", "success");
			res.put("orderId", orderId);
		} catch (Exception e) {
			e.printStackTrace();
			res.put("code", "9999");
			res.put("msg", "exception");
			res.put("orderId", null);
		}

		return JSON.toJSONString(res);
	}

	@RequestMapping("pay/{orderId}")
	public String pay(@PathVariable(name = "orderId") String orderId) {

		System.out.println("支付：" + orderId);

		Map<String, Object> res = new HashMap<>();

		try {

			PayOrder payOrder = payOrderService.queryPayOrderByOrderId(orderId);

			if (payOrder != null && payOrder.getState().equals(1)) {
				payOrder.setState(2);
				payOrderService.updateOrder(payOrder);
				res.put("code", "0000");
				res.put("msg", "支付成功");
				return JSON.toJSONString(res);
			}

			if (payOrder != null && payOrder.getState().equals(3)) {
				res.put("code", "9999");
				res.put("msg", "已超时，支付已取消");
				return JSON.toJSONString(res);
			}

			if (payOrder != null && payOrder.getState().equals(2)) {
				res.put("code", "1111");
				res.put("msg", "已支付，不能重复支付");
				return JSON.toJSONString(res);
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.put("code", "9999");
			res.put("msg", "exception");

		}

		return JSON.toJSONString(res);
	}

	@RequestMapping("getCancelOrders")
	public List<PayOrder> getCancelOrders() {


		List<PayOrder> payOrders = payOrderService.queryPayOrders(3);


		return payOrders;

	}
}
